package receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
import db.ServiceDatabase;

public class CallReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		ServiceDatabase db = new ServiceDatabase(context);
		try {
			if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
				// Log.i("EXTRA_PHONE_NUMBER",
				// intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER) + "");
				/*-Toast.makeText(context, "Call to:" + intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER), Toast.LENGTH_SHORT).show();*/
				// Goi ra
				String phone = ServiceDatabase.refinePhone(intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER));
				db.updateSeen(phone, "phone");

			} else if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED) && intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) {

				// Log.i("EXTRA_INCOMING_NUMBER",
				// intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)
				// +
				// "");
				/*-Toast.makeText(context, "Call from:" + intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER), Toast.LENGTH_SHORT).show();*/
				// Nguoi khac goi vao
				String phone = ServiceDatabase.refinePhone(intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
				db.updateSeen(phone, "phone");
			}
		} catch (Exception e) {
			Log.i("ERROR", e.getMessage());
		} finally {
			if (db != null)
				db.close();
		}
	}

}
